<?php

namespace App\Service\playlet;
use App\Model\DataOrder;
use App\Model\DataOrderPlaylet;
use App\Model\DataUser;
use App\Model\Playlet;
use App\Service\CommicService;
use Hyperf\Utils\ApplicationContext;
use App\Common\Response\SystemCode;
class DataOrderService extends CommicService
{
    const cacheDuration = 60 * 15;
    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $this->redisService = $container->get(\Hyperf\Redis\Redis::class);
    }
    const STATUS_ENABLE  = 1;
    public function search(Array $params){

        $keyword     = $params['keyword'] ?? '';
        $pageSize    = $params['pageSize'] ?? 10;
        $page        = $params['page'] ?? 1;
        $dataUsertIds = '';

        if ($keyword) {
            //查询小程序
            $dataUsertIds = DataUser::query()->orWhere([['username', 'like', '%'.$keyword.'%']])->orWhere([['real_name', 'like', '%'.$keyword.'%']])->withTrashed()->pluck('id');
        }
        $query = DataOrder::query()->select(['id','data_user_id','status','phone','created_at','updated_at']);
        if ($dataUsertIds) {

            $query->whereIn('data_user_id' ,$dataUsertIds);
        }
        $models = $query->orderBy('id','desc')->paginate($pageSize,['*'],'page',$page);
        $items = $models->items();
        $selectData = [];
        foreach ($items as $item){
            $data = $item->toArray();
            if(!empty($item->dataUser)){
                $data['data_user_name']  = $item->dataUser->real_name ?? $item->dataUser->username;
            }else{
                $data['data_user_name']  = '';
            }
            $data['status_name'] = self::$orderStatus[$item->status];

            $playletIds = DataOrderPlaylet::query()->where('data_order_id',$item->id)->pluck('playlet_id');
            if(!empty($playletIds)){
                $playletName = Playlet::query()->whereIn('id',$playletIds)->pluck('name')->toArray();
                $data['playlet_name'] =implode(",",$playletName);
            }
            $selectData[] =$data;
        }
        $data = $models->toArray();
        $data['data'] = $selectData;

        return $data;
    }


    public function createOrUpdate(Array $postData,DataOrder $dataOrderInfo){
        $status = $postData['status'] ?? 1;
        $model = $dataOrderInfo;
        $model->status = $status;
        if($model->save()){
            return $this->response(SystemCode::SYSTEM_SUCCESS);
        }else{
            return $this->response(SystemCode::SYSTEM_ERROR,'保存错误');
        }
    }

}